package org.NooLab.itexx.app.storage;

import java.io.Serializable;

import org.NooLab.itexx.ITexxWindowCommons;
import org.NooLab.itexx.ITexxWindowIntf;
import org.NooLab.itexx.app.config.ITexxAppPropertiesIntf;
import org.NooLab.itexx.app.controller.ExitActionProviderIntf;
import org.NooLab.itexx.app.controller.SessionManager;
import org.NooLab.itexx.app.gui.definition.ITexxWindowGuiIntf;
import org.NooLab.itexx.stuctures.GuiPersistenceData;
import org.NooLab.itexx.stuctures.RequestHistory;




/**
 * 
 * 
 * provides object storage
 * storage to db is elsewhere
 *
 */
public class GuiPersistence implements ExitActionProviderIntf, Serializable {

	transient static GuiPersistence guiPersistence;
	transient ITexxWindowIntf app;
	transient ITexxWindowGuiIntf windowGui;
	transient ITexxWindowCommons appCommons;

	transient ITexxAppPropertiesIntf appProperties;

	GuiPersistenceData guiData;

	// ========================================================================
	public GuiPersistence(ITexxWindowIntf app, ITexxWindowGuiIntf windowGui) {

		this.app = app;
		this.windowGui = windowGui;
		
		appCommons = app.getAppCommons();
		
		appProperties = app.getAppCommons().getAppProperties();

		guiData = new GuiPersistenceData();

		guiPersistence = this;
	}

	// ========================================================================

	public static GuiPersistence getInstance(ITexxWindowIntf app, ITexxWindowGuiIntf windowGui) {

		if (guiPersistence == null) {
			guiPersistence = new GuiPersistence(app, windowGui);
		}
		return guiPersistence;
	}

	public GuiPersistenceData getGuiData() {
		return guiData;
	}

	public void setGuiData(GuiPersistenceData guidata) {

		if (guiData != null) {
			guiData = guidata;
		} else {
			appProperties.setGuiData(guiData);
		}
	}

	// from ExitActionProviderIntf
	@Override
	public int perform(ITexxWindowIntf app) {

		SessionManager smgr;
		RequestHistory rqHistory;

		//
		if (windowGui == null) {
			windowGui = app.getWindowGui();
		}

		if (guiData == null) {
			guiData = new GuiPersistenceData();
		}
		guiData.getFocusSettings(windowGui);

		// the list of results

		//
		appProperties.setGuiData(guiData);

		smgr = appCommons.getSessionManager();
		rqHistory = smgr.getRequestHistory();

		// finally, save all to a file, actually, to TWO files:
		// - a dedicated properties file (without results)
		// - a persistence file, with a link to properties file,
		// and which else includes the result list, and the search history

		String filename = appProperties.getConfigFilename();
		appCommons.getStorage().writeFile(appProperties, filename);

		return 0;
	}

}
